using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;

using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;

using RealDolmen.SharePoint.Controls;
using RealDolmen.SharePoint.Helpers;
using RealDolmen.SharePoint.ListFeatures.Controls;
using RealDolmen.SharePoint.ListFeatures.Elements;

namespace RealDolmen.SharePoint.ListFeatures
{
    public class SettingsPage : FixedLayoutsPageBase
    {
        #region Properties
        private ListFeature listFeature;

        protected ListFeature ListFeature
        {
            get
            {
                if (listFeature == null)
                    listFeature = ListFeature.Current;
                return listFeature;
            }
        }
        #endregion // Properties

        #region Rendering
        protected void RenderAll()
        {
            RenderGeneralInformation();
            RenderCustomizations();
        }

        protected void RenderCustomizations()
        {
            HtmlTextWriter writer = new HtmlTextWriter(Response.Output);
            writer.WriteLine("<table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">");

            RenderSettings();
            if(ListFeature.Definition.HasCustomizableElements)
            {
                RenderSectionTitle(GetGlobalResourceObject("lf", "ListFeaturesSettingsTitleElements").ToString());
                RenderSpacing();
                RenderTimerJobs();
                RenderSpacing();
                RenderMenuItems();
                RenderSpacing();
            }
            RenderButtons();
            writer.WriteLine("</table>");
        }

        protected void RenderGeneralInformation()
        {
            Literal literal;
            HtmlTextWriter writer = new HtmlTextWriter(Response.Output);
            ITemplate template = SPControlTemplateManager.GetTemplateByName("ListFeatureInformation");

            if (template != null)
            {
                TemplateContainer container = new TemplateContainer();
                template.InstantiateIn(container);


                // Title area
                if (ListFeature.Definition.Exists)
                {
                    if (ListFeature.IsActive)
                    {
                        Button button = container.FindControl("btnDeactivateFeature") as Button;
                        button.Visible = true;
                        button.Attributes["onmouseover"] = string.Format("rollover(this, '{0}');", GetGlobalResourceObject("wss", "ManageFeatures_Deactivate"));
                        button.Attributes["onmouseout"] = "rollout(this);";
                    }
                    else
                    {
                        Button button = container.FindControl("btnActivateFeature") as Button;
                        button.Visible = true;
                        button.Attributes["onmouseover"] = string.Format("rollover(this, '{0}');", GetGlobalResourceObject("wss", "ManageFeatures_Activate"));
                        button.Attributes["onmouseout"] = "rollout(this);";
                    }
                }
                else
                {
                    Button button = container.FindControl("btnErrorFeature") as Button;
                    button.Visible = true;
                    button.ToolTip = HttpContext.GetGlobalResourceObject("lf", "ListFeaturesErrorNotInstalledNotActive").ToString();
                }

                TextBox tb = container.FindControl("tbTitle") as TextBox;
                tb.Text = ListFeature.GetTitle(SPHelper.CurrentCultureInfo);
                tb.Columns = 60;
                MakeWatermark(tb, ListFeature.Definition.GetTitle(SPHelper.CurrentCultureInfo));

                tb.ID = ListFeature.ConvertKey(
                                ListFeature.Keys.Title,
                                RetrievalMethod.Identity);

                // Type area
                literal = container.FindControl("litTypeText") as Literal;
                literal.Text = string.Format(GetGlobalResourceObject("lf", "ListFeaturesSettingsTypeText").ToString(),
                    string.Format("{0} {1}",
                         ListFeature.Definition.GetTitle(SPHelper.CurrentCultureInfo),
                         ListFeature.Definition.Version),
                    string.Format("<a href=\"{0}\" title=\"{1}\">{1}</a>",
                        ListFeature.ParentList.DefaultViewUrl,
                        ListFeature.ParentList.Title)
                );

                // Description area
                literal = container.FindControl("litDescriptionText") as Literal;
                literal.Text = ListFeature.Definition.GetDescription(SPHelper.CurrentCultureInfo);

                container.RenderControl(writer);
            }
        }
        #endregion // Rendering

        #region Settings
        protected void RenderSettings()
        {
            List<ListFeatureSetting> settings = ListFeature.Settings.Get();

            if (settings.Count > 0)
            {
                RenderSectionTitle(GetGlobalResourceObject("lf", "ListFeaturesSettingsTitleSettings").ToString());
                RenderSpacing();
                foreach (ListFeatureSetting setting in settings)
                {
                    RenderSetting(setting);
                }
                RenderSpacing();
            }
        }

        protected void RenderSetting(ListFeatureSetting setting)
        {
            HtmlTextWriter writer = new HtmlTextWriter(Response.Output);

            InputFormSection formSection = Page.LoadControl("/_controltemplates/InputFormSection.ascx") as InputFormSection;

            if (formSection != null)
            {
                Literal title = formSection.FindControl("LiteralTitle") as Literal;
                title.Text = setting.Name;

                PlaceHolder controls = formSection.FindControl("PlaceHolderControls") as PlaceHolder;

                TextBox value = new TextBox();
                value.Columns = 60;
                value.ID = setting.ConvertKey(
                            ListFeatureSetting.Keys.Value,
                            RetrievalMethod.Identity);
                value.Text = setting.Value;
                MakeWatermark(value, setting.DefaultValue);

                controls.Controls.Add(value);

                formSection.RenderControl(writer);
            }
        }

        protected void RenderSetting(string name)
        {
            ListFeatureSetting setting = ListFeature.Settings.Get(name);

            if (setting != null)
                RenderSetting(setting);
        }
        #endregion // Settings

        #region Elements: TimerJobs
        protected void RenderTimerJobs()
        {
            List<ListFeatureTimerJobElement> timerJobs = ListFeature.Elements.Get<ListFeatureTimerJobElement>();
            foreach (ListFeatureTimerJobElement timerJob in timerJobs)
            {
                RenderTimerJob(timerJob);
            }
        }

        private void RenderTimerJob(ListFeatureTimerJobElement timerJob)
        {
            HtmlTextWriter writer = new HtmlTextWriter(Response.Output);

            InputFormSection formSection = Page.LoadControl("/_controltemplates/InputFormSection.ascx") as InputFormSection;

            if (formSection != null)
            {
                Literal title = formSection.FindControl("LiteralTitle") as Literal;
                title.Text = timerJob.Title;

                PlaceHolder controls = formSection.FindControl("PlaceHolderControls") as PlaceHolder;

                LiteralControl litDescription = new LiteralControl();
                litDescription.Text = GetGlobalResourceObject("lf", "ListFeaturesSettingsTimerJobDescription").ToString();
                controls.Controls.Add(litDescription);

                DropDownList ddList = new DropDownList();
                ddList.ID = timerJob.ConvertKey(
                            ListFeatureTimerJobElement.Keys.ServerString,
                            RetrievalMethod.Identity);
                ddList.Items.Add(string.Empty);
                SPServerCollection servers = SPFarm.Local.Servers;
                foreach (SPServer server in servers)
                {
                    if(server.Role == SPServerRole.Application)
                        ddList.Items.Add(server.Name);
                }
                ddList.SelectedValue = timerJob.ServerString;
                controls.Controls.Add(ddList);

                LiteralControl litBreak = new LiteralControl();
                litBreak.Text = "<br />";
                controls.Controls.Add(litBreak);

                ScheduleSelector scheduleSelector = new ScheduleSelector();
                scheduleSelector.ID = timerJob.ConvertKey(
                            ListFeatureTimerJobElement.Keys.ScheduleString,
                            RetrievalMethod.Identity);
                scheduleSelector.ScheduleString = timerJob.ScheduleString;

                controls.Controls.Add(scheduleSelector);


                formSection.RenderControl(writer);
            }
        }
        #endregion // Elements: MenuItems

        #region Elements: MenuItems
        protected void RenderMenuItems()
        {
            List<ListFeatureCustomActionElement> elements = ListFeature.Elements.Get<ListFeatureCustomActionElement>();
            foreach (ListFeatureCustomActionElement element in elements)
            {
                RenderMenuItem(element);
            }
        }

        private void RenderMenuItem(ListFeatureCustomActionElement customAction)
        {
            HtmlTextWriter writer = new HtmlTextWriter(Response.Output);

            InputFormSection formSection = Page.LoadControl("/_controltemplates/InputFormSection.ascx") as InputFormSection;

            if (formSection != null)
            {
                string defaultTitle = customAction.GetDefaultAttribute(ListFeatureCustomActionElement.Keys.Title);
                Literal title = formSection.FindControl("LiteralTitle") as Literal;
                title.Text = string.Format(
                    GetGlobalResourceObject("lf", "ListFeaturesSettingsCustomActionTitle").ToString(),
                    defaultTitle);

                PlaceHolder controls = formSection.FindControl("PlaceHolderControls") as PlaceHolder;

                TextBox tbValue = new TextBox();
                tbValue.Columns = 60;
                tbValue.ID = customAction.ConvertKey(
                            ListFeatureCustomActionElement.Keys.Title,
                            RetrievalMethod.Identity);
                tbValue.Text = customAction.Title;
                MakeWatermark(tbValue, defaultTitle);

                controls.Controls.Add(tbValue);

                formSection.RenderControl(writer);
            }
        }
        #endregion // Elements: MenuItems

        #region Buttons
        private void RenderButtons()
        {
            HtmlTextWriter writer = new HtmlTextWriter(Response.Output);
            ButtonSection buttonSection = Page.LoadControl("/_controltemplates/ButtonSection.ascx") as ButtonSection;

            if (buttonSection != null)
            {
                RepeatedControls buttons = buttonSection.FindControl("RptControls") as RepeatedControls;

                buttons.Controls.Add(GenerateButton("Delete", "Delete"));
                
                if(ListFeature.Definition.Exists)
                    buttons.Controls.Add(GenerateButton(ToggleActivationButtonText, "ToggleActivation"));
                
                buttons.Controls.Add(GenerateButton(GetGlobalResourceObject("lf", "ListFeaturesSettingsButtonsOk").ToString(), "Ok"));
                buttons.Controls.Add(GenerateButton(GetGlobalResourceObject("lf", "ListFeaturesSettingsButtonsCancel").ToString()));

                PlaceHolder buttonCancel = buttonSection.FindControl("PlaceHolderButtonCancel") as PlaceHolder;
                buttonCancel.Controls.Clear();

                buttonSection.RenderControl(writer);
            }
        }

        private Button GenerateButton(string name)
        {
            return GenerateButton(name, name);
        }

        private Button GenerateButton(string name, string id)
        {
            Button tb = new Button();
            tb.UseSubmitBehavior = false;
            tb.Attributes["class"] = "ms-ButtonHeightWidth";
            tb.Text = name;
            tb.ID = id;
            return tb;
        }

        private string ToggleActivationButtonText
        {
            get
            {
                if(ListFeature.IsActive)
                    return GetGlobalResourceObject("wss", "ManageFeatures_Deactivate").ToString();
                else
                    return GetGlobalResourceObject("wss", "ManageFeatures_Activate").ToString();
            }
        }
        #endregion // Buttons

        #region Render Helpers
        protected void MakeWatermark(TextBox textBox, string watermark)
        {
            textBox.Attributes["onfocus"] = string.Format("setfocus(this, '{0}');", watermark);
            textBox.Attributes["onblur"] = string.Format("setblur(this, '{0}');", watermark);
            if (watermark == textBox.Text)
                textBox.Attributes["class"] = "inactiveText";
        }

        protected void RenderSpacing()
        {
            HtmlTextWriter writer = new HtmlTextWriter(Response.Output);
            writer.Write(
                "		<tr>" +
                "			<td height=\"10px\" class=\"ms-descriptiontext\" colspan=\"2\"><IMG SRC=\"/_layouts/images/blank.gif\" width=\"1\" height=\"10\"></td>" +
                "		</tr>");
        }

        protected void RenderSectionTitle(string title)
        {
            HtmlTextWriter writer = new HtmlTextWriter(Response.Output);
            writer.Write(
                "		<tr>" +
                "			<td height=\"10px\" class=\"ms-linksectionheader\" style=\"padding:4px\" colspan=\"2\"><h3 class=\"ms-standardheader\">" + title + "</h2></td>" +
                "		</tr>");
        }
        #endregion // Render Helpers

        #region Events
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (Page.IsPostBack)
            {
                if (Request.Params["__EVENTTARGET"] == "btnDeactivateFeature")
                {
                    ListFeature.Deactivate();
                }
                else if (Request.Params["__EVENTTARGET"] == "btnActivateFeature")
                {
                    ListFeature.Activate();
                }
                else
                {
                    if (Request.Params["__EVENTTARGET"] == "RptControls$Ok")
                    {
                        SaveRequestedChanges();
                    }
                    else if (Request.Params["__EVENTTARGET"] == "RptControls$ToggleActivation")
                    {
                        SaveRequestedChanges();

                        if (ListFeature.IsActive)
                            ListFeature.Deactivate();
                        else
                            ListFeature.Activate();
                    }
                    else if (Request.Params["__EVENTTARGET"] == "RptControls$Delete")
                    {
                        ListFeature.Delete();
                    }

                    SPUtility.Redirect("ManageListFeatures.aspx",
                        SPRedirectFlags.RelativeToLayoutsPage,
                        HttpContext.Current,
                        string.Format("List={0}", ListFeature.ParentList.ID));
                }
            }
        }

        protected void SaveRequestedChanges()
        {
            // Title
            ListFeature.SetTitle(ListFeature.GetFromCollection(
                ListFeature.Keys.Title,
                Request.Params,
                RetrievalMethod.Identity));

            // Settings
            List<ListFeatureSetting> settings = ListFeature.Settings.Get();
            foreach (ListFeatureSetting setting in settings)
            {
                setting.Value = setting.GetFromCollection(
                    ListFeatureSetting.Keys.Value,
                    Request.Params, 
                    RetrievalMethod.Identity);
            }

            // TimerJobs
            List<ListFeatureTimerJobElement> timerJobs = ListFeature.Elements.Get<ListFeatureTimerJobElement>();
            foreach (ListFeatureTimerJobElement timerJob in timerJobs)
            {
                timerJob.ScheduleString = timerJob.GetFromCollection(
                   ListFeatureTimerJobElement.Keys.ScheduleString,
                   Request.Params,
                   RetrievalMethod.Identity);
                timerJob.ServerString = timerJob.GetFromCollection(
                    ListFeatureTimerJobElement.Keys.ServerString,
                    Request.Params,
                    RetrievalMethod.Identity);
            }

            // MenuItems
            List<ListFeatureCustomActionElement> customActions = ListFeature.Elements.Get<ListFeatureCustomActionElement>();
            foreach (ListFeatureCustomActionElement customAction in customActions)
            {
                customAction.Title = customAction.GetFromCollection(
                    ListFeatureCustomActionElement.Keys.Title,
                    Request.Params,
                    RetrievalMethod.Identity);
            }
        }
        #endregion // Events
    }
}
